package offer;

public class offerII_0022 {
    public ListNode detectCycle(ListNode head) {
        ListNode p=head;
        ListNode q=head;
        if(q==null||q.next==null||q.next.next==null) return null;
        while(q!=null){
            p=p.next;
            if(q.next==null) return null;
            q=q.next;
            if(q.next==null) return null;
            q=q.next;
            if(p==q){
                break;
            }
        }
        if(q==null) return null;
        p=head;
        while(p!=q){
            p=p.next;
            q=q.next;
        }
        return p;
    }
}
